package bTree.LeetCode;

import javax.swing.tree.TreeNode;
import java.util.Arrays;

public class 从中序与后序遍历序列构造二叉树 {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int length = inorder.length;
        if(length==0){
            return null;
        }
        TreeNode root=new TreeNode(postorder[length-1]);
        int index=-1;
        for (int i = 0; i < length; i++) {
            if(inorder[i]==root.val){
                index=i;
                break;
            }
        }
        int []leftInorder= Arrays.copyOfRange(inorder,0,index);
        int []rightInorder= Arrays.copyOfRange(inorder,index+1,length);
        int []leftPostorder=Arrays.copyOfRange(postorder,0,index);
        int []rightPostorder=Arrays.copyOfRange(postorder,index,length-1);
        root.left=buildTree(leftInorder,leftPostorder);
        root.right=buildTree(rightInorder,rightPostorder);
        return root;
    }
}